package com.autonavi.yunda.yunji.common.web;

import org.apache.logging.log4j.util.Strings;
import org.jetbrains.annotations.NotNull;
import org.slf4j.MDC;
import org.springframework.util.DigestUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

import static com.autonavi.yunda.yunji.common.constant.CommonConstant.HEADER_TRACE_ID;
import static com.autonavi.yunda.yunji.common.constant.CommonConstant.MDC_TRACE_ID;


/**
 * 增加日志标识的： 日后查一下这块的知识点： Logback的官方文档，详细介绍了MDC的工作原理和使用方式。 TODO
 * @author cizhong.wcs
 * @date 2022/1/30 11:49 上午
 */
public class AmapTraceIdFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    @NotNull HttpServletResponse response,
                                    @NotNull FilterChain filterChain)
            throws ServletException, IOException {
        String traceId = request.getHeader(HEADER_TRACE_ID);
        if (Strings.isEmpty(traceId)) {
            traceId = DigestUtils.md5DigestAsHex(UUID.randomUUID().toString().getBytes());
        }
        MDC.put(MDC_TRACE_ID, traceId);
        super.doFilter(request, response, filterChain);
        MDC.remove(MDC_TRACE_ID);
    }

}
